package com.keyinong.caizhengting.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.keyinong.caizhengting.R;
import com.keyinong.caizhengting.tools.HttpTools;
import com.keyinong.caizhengting.tools.NetWorkUtil;
import com.keyinong.caizhengting.adapter.SearchAdapter;
import com.keyinong.caizhengting.entity.ShangpinEntity;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * @author：郑谦
 * @时间：2017-4-10 下午4:02:27
 * @类名：CommentActivity.java
 * @功能: 搜索(暂时不用)
 */

public class SearchActivity extends Activity {

    HttpTools toolModel = new HttpTools(SearchActivity.this);
    int width;
    int height;
    private EditText et_sousuo;
    private ImageButton ib_fanhui;
    private ImageButton ib_sousuo;
    private PullToRefreshListView pull_sousuo;
    private TextView tv_none;
    /**
     * 商品信息的集合
     */
    private ArrayList<ShangpinEntity> goodslist;
    private int offset = 0;
    private int page = 10;
    private SearchAdapter adapter;
    private String id;
    private String token;
    private String spid;
    private String spname;
    private String spprice;
    private String spamount;
    private String arraylength;
    private String name = "1";
    OnKeyListener onKey = new OnKeyListener() {

        @Override

        public boolean onKey(View v, int keyCode, KeyEvent event) {

            // TODO Auto-generated method stub

            if (keyCode == KeyEvent.KEYCODE_ENTER) {

                InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);

                if (imm.isActive()) {

                    imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                    getGoodsinfo();
                }

                return true;

            }

            return false;

        }

    };
    private OnItemClickListener itemclicke = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int position,
                                long id) {
            Intent intent = new Intent();
            intent.putExtra("productid", goodslist.get(position).getId());
//			intent.setClass(SearchActivity.this, ProductDetailActivity.class);
            startActivity(intent);
//			ProductDetailFragemnt meetingFragment = new ProductDetailFragemnt();
//			Bundle bundle=new Bundle();
//			bundle.putString("productid",goodslist.get(position).getId());
//			replceFragment(meetingFragment,bundle);
//			Meg(3);
        }
    };
    /**
     * 上下拉刷新
     */
    private OnRefreshListener2<ListView> onrefresh = new OnRefreshListener2<ListView>() {

        @Override
        public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
            offset = 0;
//			goodslist.clear();
            goodslist.clear();
            name = et_sousuo.getText().toString();

//			ib_sousuo.setEnabled(true);
            if (name.equals("")) {
//				pull_sousuo.removeAllViews();
                Log.i("zq", "1----");
                tv_none.setVisibility(View.VISIBLE);
                Toast.makeText(SearchActivity.this, "没有查询到商品", Toast.LENGTH_SHORT).show();

//				adapter.notifyDataSetChanged();
                pull_sousuo.onRefreshComplete();

//				return;
//				ib_sousuo.setEnabled(false);
            } else {
                Log.e("zq", "token---" + token);
                Log.e("zq", "name---" + name);
                Log.e("zq", "page---" + page);
                Log.e("zq", "offset---" + offset);
                toolModel.searchProduct(token, name, page + "", offset + "",
                        new JsonGetGoodsInfo());
                if (NetWorkUtil.isNetwork(getApplicationContext()) == false) {
//				MyToast.mytoast(getActivity(), "当前网络不可用");
                    Toast.makeText(SearchActivity.this, "当前网络不可用", Toast.LENGTH_SHORT).show();
                    pull_sousuo.onRefreshComplete();
                    return;
                }
            }
        }


        @Override
        public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
            offset += page;
//			name=et_sousuo.getText().toString();
//			Log.i("zq", "token----"+token);
//			Log.i("zq", "name----"+name);
//			Log.i("zq", "page----"+page);
//			Log.i("zq", "offset----"+offset);
//			toolModel = new HttpTools(SearchActivity.this);
            name = et_sousuo.getText().toString();
//			ib_sousuo.setEnabled(true);
            if (name.equals("")) {
                goodslist.clear();
//				tv_none.setVisibility(View.VISIBLE);
                Toast.makeText(SearchActivity.this, "没有查询到商品", Toast.LENGTH_SHORT).show();
                pull_sousuo.onRefreshComplete();
                return;
            } else {
                toolModel = new HttpTools(SearchActivity.this);
                toolModel.searchProduct(token, name, page + "", offset + "",
                        new JsonGetGoodsInfo());
                if (NetWorkUtil.isNetwork(getApplicationContext()) == false) {
                    Toast.makeText(getApplicationContext(), "当前网络不可用", Toast.LENGTH_SHORT).show();
                    pull_sousuo.onRefreshComplete();
                    return;
                }
            }

//			setSection();
//			adapter.notifyDataSetChanged();

        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//			getWindow().addFlags(
//					WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_search);
        initRes();
    }

    private void initRes() {
        goodslist = new ArrayList<ShangpinEntity>();
        SharedPreferences spwm = getSharedPreferences("spWM",
                Context.MODE_PRIVATE);
        width = spwm.getInt("width", 720);
        height = spwm.getInt("height", 1280);
        SharedPreferences sp = getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        token = sp.getString("data", "");
        pull_sousuo = (PullToRefreshListView) findViewById(
                R.id.pull_sousuo);

        pull_sousuo.setMode(Mode.BOTH);
        pull_sousuo.setOnRefreshListener(onrefresh);
//		pull_sousuo.setOnItemClickListener(itemclicke);
        et_sousuo = (EditText) findViewById(R.id.et_sousuo);
        ib_fanhui = (ImageButton) findViewById(R.id.ib_fanhui);
        ib_sousuo = (ImageButton) findViewById(R.id.ib_sousuo);
        tv_none = (TextView) findViewById(R.id.tv_none);
        tv_none.bringToFront();
        et_sousuo.setOnKeyListener(onKey);

//		getGoodsinfo();
        ib_fanhui.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ib_sousuo.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                getGoodsinfo();
                Log.i("info", "-----------");
            }
        });

    }

    private void getGoodsinfo() {
//		goodslist = new ArrayList<ShangpinEntity>();
        goodslist = new ArrayList<ShangpinEntity>();
        name = et_sousuo.getText().toString();
        if (name.equals("")) {
            Toast.makeText(getApplicationContext(), "请输入商品名", Toast.LENGTH_SHORT).show();
//			ib_sousuo.setEnabled(false);
            return;
        }
        Log.i("info", "-----------" + name);
        if (toolModel == null) {
            toolModel = new HttpTools(SearchActivity.this);
            Log.i("info", "*********" + name);
        }
//		toolModel = new HttpTools(getApplicationContext());
        toolModel.searchProduct(token, et_sousuo.getText().toString(), page + "", offset + "",
                new JsonGetGoodsInfo());
//		ib_sousuo.setEnabled(false);
    }

    private class JsonGetGoodsInfo extends JsonHttpResponseHandler {

        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONArray response) {
            super.onSuccess(statusCode, headers, response);
            Log.i("info", "sousuo---------" + response.toString());

            try {
                Log.i("info", "分类加载----" + response.toString());
                for (int i = 0; i < response.length(); i++) {
                    JSONObject data = response.getJSONObject(i);
                    id = data.getString("id");
                    String name = data.getString("name");
                    String content = data.getString("content");
                    String price = data.getString("price");
                    String image = data.getString("image");
                    String unit = data.getString("unit");
                    String stock = data.getString("stock");
                    String perlim = data.getString("perlim");
                    String daylim = data.getString("daylim");
                    String sellnum = data.getString("sellnum");
                    String amount = data.getString("amount");
                    String buyamount = data.getString("buyamount");

                    goodslist.add(new ShangpinEntity(id, name, image, content, price, amount, unit, stock, perlim, daylim, sellnum, buyamount));
                }
                if (goodslist.size() == 0) {
                    tv_none.setVisibility(View.VISIBLE);
                    Toast.makeText(getApplicationContext(), "没有查询到商品", Toast.LENGTH_SHORT).show();
//					ib_sousuo.setEnabled(true);
//					name="";
                } else {
                    tv_none.setVisibility(View.GONE);
                }
//				name="";
//				et_sousuo.setText("");
                adapter = new SearchAdapter(SearchActivity.this, goodslist);
                pull_sousuo.setAdapter(adapter);
                pull_sousuo.getRefreshableView().setSelection(offset);
                //				lv.setDivider(null);
//				Utility.setGridViewHeightBasedOnChildren(pull_twosort);
                pull_sousuo.onRefreshComplete();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }


//	public void Meg(int i) {
//		Message message = Message.obtain();
//		message.what = i;
//		FanqiedingcanActivity.mHandler.sendMessage(message);
//	}
//	private void replceFragment(Fragment fragment,Bundle bundle) {
//		FragmentManager fManager = getApplicationContext().getFragmentManager();
//		FragmentTransaction fTransaction = fManager.beginTransaction();
//		fragment.setArguments(bundle);
//		fTransaction.replace(R.id.fram_fanqiedingcan, fragment);
//		fTransaction.commit();
//	}

}
